<!--
 * @FileDescription: 装置内容
 * @Author: 祝小文
 * @Date: 2022-09-28 16:17
-->
<script setup lang="ts">
import { emitter } from '@/composables'
import _ from 'lodash'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import sb_icon from '@/assets/image/mapIcon/sb-icon.png'
import SecondaryConfirm from '@/components/SecondaryConfirm/index.vue'
import { featureClick, delMapFactorInfo, flyToLxOrCjid } from '@/utils/common/index'
import {
  querySearchInfo,
  insertOrUpdateZZXX,
  insertOrUpdateDYXX,
  insertOrUpdateSBXX,
} from '@/service/api'

const chemicalStore = useChemicalStore()
const device = chemicalStore.productionStorage.device

const emit = defineEmits(['getCjInfo'])

//获取企业id
const qyId = computed(() => {
  return chemicalStore.qyInfo.id
})

//字典
//查询设备类型
queryZdZdmcInfo({ key: 'zdsblx' }).then((res: any) => {
  device.dictionaries.zdsblx = res
})

const dyActive: any = ref([])
const input = ref('')
const deviceList = ref([])

//搜索功能(300毫秒防抖)
const inputSearch = _.debounce((val: any) => {
  const params = {
    menuCode: 'zz',
    key: val,
    qyid: qyId.value,
  }
  querySearchInfo(params).then((res: any) => {
    deviceList.value = res

    //折叠面板打开项 为空就折叠所有面板
    for (let i = 0; i < res.length; i++) {
      dyActive.value.push(i)
    }
    if (!val) {
      dyActive.value = []
    }
  })
}, 300)

//装置/单元/设备 删除数据/删除地图要素 确认
const secondaryConfirmSave = (type: any, typeCode: any) => {
  const item: any = chemicalStore.secondaryConfirmInfo.data

  //删除地图要素数据
  if (type === 'delMapData') {
    if (typeCode === 'zz') {
      delMapFactorInfo(item, 'scrollWall')
    } else if (typeCode === 'dy') {
      delMapFactorInfo(item, 'scrollWall')
    } else if (typeCode === 'sb') {
      delMapFactorInfo(item, 'overlay')
    }
  }
  //删除数据
  else if (type === 'delData') {
    if (typeCode === 'zz') {
      const params = { id: item.id, qyid: item.qyid, sfyx: 0 }

      insertOrUpdateZZXX(params)
        .then((res: any) => {
          emitter.emit('tabLeft_refreshData') //更新左侧tab统计数量

          //删除地图要素
          window.GScrollWall.removeByName(item.id)

          window.GOverlay.removeByPatName(item.id)

          let dyId //获取单元id
          window.GScrollWallArray.forEach((el: any) => {
            if (el.parentName === item.id) {
              dyId = el.name
            }
          })
          window.GScrollWall.removeByPatName(item.id)
          if (dyId) {
            window.GOverlay.removeByPatName(dyId)
          }

          ElMessage.success('装置删除成功')
          loadDeviceData()
        })
        .catch((err: any) => {
          ElMessage.error('装置删除失败')
        })
    } else if (typeCode === 'dy') {
      const params = { id: item.id, qyid: item.qyid, sfyx: 0 }

      insertOrUpdateDYXX(params)
        .then((res: any) => {
          //删除地图要素
          window.GScrollWall.removeByName(item.id)
          window.GOverlay.removeByPatName(item.id)

          ElMessage.success('单元删除成功')
          loadDeviceData()
        })
        .catch((err: any) => {
          ElMessage.error('单元删除失败')
        })
    } else if (typeCode === 'sb') {
      const params = { id: item.id, qyid: item.qyid, sfyx: 0 }

      insertOrUpdateSBXX(params)
        .then((res: any) => {
          //删除地图要素
          window.GOverlay.removeByName(item.id)

          ElMessage.success('设备删除成功')
          loadDeviceData()
        })
        .catch((err: any) => {
          ElMessage.error('设备删除失败')
        })
    }
  }
}

/** ---------- 装置相关方法 Start ---------- */
//加载装置数据
const loadDeviceData = () => {
  const params = {
    menuCode: 'zz',
    qyid: qyId.value,
  }
  querySearchInfo(params).then((res: any) => {
    deviceList.value = res
  })
}
loadDeviceData()

//新增装置
const addDeviceClick = () => {
  chemicalStore.closeAllPSDialog() //关闭全部弹窗
  emit('getCjInfo', { cjId: null, fid: null, lx: 'add' })
  device.addDeviceShow = true
}
//删除装置
const delDevice = (item: any) => {
  chemicalStore.secondaryConfirmInfo = {
    show: true,
    text: '是否确定删除装置以及该装置下单元信息和设备信息',
    type: 'delData',
    typeCode: 'zz',
    data: item,
  }
}
//修改装置
const updateDeviceClick = (item: any) => {
  chemicalStore.closeAllPSDialog() //关闭全部弹窗
  emit('getCjInfo', { cjId: item.id, fid: null, lx: 'edit' })
  device.addDeviceShow = true
}

//装置上图
const addMapDeviceClick = (item: any) => {
  featureClick({
    id: item.id,
    parentName: item.id,
    MapFactorType: 'scrollWall',
    MapFactorName: '装置区',
    bzlx: '7',
    text: item.mc,
    attribute: item,
  })
}
//装置地图要素删除
const delMapDeviceClick = (item: any) => {
  chemicalStore.secondaryConfirmInfo = {
    show: true,
    text: '是否确定删除该装置地图要素',
    type: 'delMapData',
    typeCode: 'zz',
    data: item,
  }
}

//装置选中事件
const deviceActiveIndex = ref(0)
const activeDeviceClick = (item: any) => {
  flyToLxOrCjid('scrollWall', item.id)
  deviceActiveIndex.value = item.id
  tankUnitIndex.value = 0
  equipmentActiveIndex.value = 0
}
/** ---------- 装置相关方法 End ---------- */

/** ---------- 单元相关方法 Start ---------- */
//新增单元
const addUnitClick = (zzItem: any) => {
  chemicalStore.closeAllPSDialog() //关闭全部弹窗
  emit('getCjInfo', { cjId: null, fid: zzItem.id, lx: 'add' })
  device.addUnitShow = true
}
//删除单元
const delUnit = (item: any) => {
  chemicalStore.secondaryConfirmInfo = {
    show: true,
    text: '是否确定删除单元以及该单元下设备信息',
    type: 'delData',
    typeCode: 'dy',
    data: item,
  }
}
//修改单元
const updateUnitClick = (item: any) => {
  chemicalStore.closeAllPSDialog() //关闭全部弹窗
  emit('getCjInfo', { cjId: item.id, fid: item.fid, lx: 'edit' })
  device.addUnitShow = true
}

//单元上图
const addMapUnitClick = (item: any) => {
  featureClick({
    id: item.id,
    parentName: item.fid,
    MapFactorType: 'scrollWall',
    MapFactorName: '单元',
    bzlx: '9',
    text: item.mc,
    attribute: item,
  })
}
//单元地图要素删除
const delMapUnitClick = (item: any) => {
  chemicalStore.secondaryConfirmInfo = {
    show: true,
    text: '是否确定删除该单元地图要素',
    type: 'delMapData',
    typeCode: 'dy',
    data: item,
  }
}

//单元选中事件
const tankUnitIndex = ref(0)
const activeUnitClick = (item: any, deviceItem: any) => {
  flyToLxOrCjid('scrollWall', item.id)
  tankUnitIndex.value = item.id
  equipmentActiveIndex.value = 0
  deviceActiveIndex.value = deviceItem.id
}
/** ---------- 单元相关方法 End ---------- */

/** ---------- 设备相关方法 Strat ---------- */
//新增设备
const addEquipmentClick = (dyItem: any, fidType: any) => {
  chemicalStore.closeAllPSDialog() //关闭全部弹窗
  emit('getCjInfo', { cjId: null, fid: dyItem.id, fidType, lx: 'add' })
  device.addEquipmentShow = true
}
//删除设备
const delEquipment = (item: any) => {
  chemicalStore.secondaryConfirmInfo = {
    show: true,
    text: '是否确定删除设备',
    type: 'delData',
    typeCode: 'sb',
    data: item,
  }
}
//修改设备
const updateEquipmentClick = (item: any, fidType: any) => {
  chemicalStore.closeAllPSDialog() //关闭全部弹窗
  emit('getCjInfo', { cjId: item.id, fid: item.fid, fidType, lx: 'edit' })
  device.addEquipmentShow = true
}

//设备上图
const addMapEquipmentClick = (item: any) => {
  // if (item.zdsblx !== '1' && item.zdsblx !== '2') {
  //   return ElMessage.warning('设备类型为塔和釜才能标注')
  // }

  featureClick({
    id: item.id,
    parentName: item.fid,
    MapFactorType: 'overlay',
    MapFactorName: '设备',
    bzlx: '9',
    text: `${item.bh} ${item.mc}`,
    mapIconUrl: sb_icon,
    parentMenuId: item.parentId,
    attribute: item,
  })
}
//设备地图要素删除
const delMapEquipmentClick = (item: any) => {
  chemicalStore.secondaryConfirmInfo = {
    show: true,
    text: '是否确定删除该设备地图要素',
    type: 'delMapData',
    typeCode: 'sb',
    data: item,
  }
}

//设备选中事件
const equipmentActiveIndex = ref(0)
const activeEquipmentClick = (item: any, unitItem: any, deviceItem: any) => {
  flyToLxOrCjid('overlay', item.id)

  equipmentActiveIndex.value = item.id
  if (unitItem) {
    tankUnitIndex.value = unitItem.id
  }
  deviceActiveIndex.value = deviceItem.id
}
/** ---------- 设备相关方法 End ---------- */

/** 监听是否需要刷新数据 */
emitter.on('zz_refreshData', () => {
  //如果输入框中有值
  if (input.value) {
    inputSearch(input.value)
    return
  }
  loadDeviceData()
})

/** 离开时销毁改事件 */
onUnmounted(() => {
  emitter.off('zz_refreshData')
})
</script>

<template>
  <div class="device-container">
    <el-input
      v-model.trim="input"
      placeholder="请输入编号或名称"
      size="large"
      :suffix-icon="Search"
      class="card-search card-bck-color"
      @input="inputSearch"
    />

    <div class="device-main">
      <div
        v-for="(zzItem, zzIndex) in deviceList"
        :key="zzIndex"
        class="device-card"
        :class="{ 'device-active': zzItem.id === deviceActiveIndex }"
        @click="activeDeviceClick(zzItem)"
      >
        <div class="device-card-top">
          <div style="display: flex; align-items: center">
            <i></i>
            <span class="single-line-text-exceeds" style="width: 260px" :title="zzItem.mc">{{
              zzItem.mc
            }}</span>
          </div>
          <div class="card-operation-btn">
            <!-- 装置数据修改 -->
            <i title="编辑表单" @click.stop="updateDeviceClick(zzItem)"></i>

            <!-- 装置地图要素上图 -->
            <i
              v-if="zzItem.sfbh === 0"
              title="标注"
              class="map-add"
              @click.stop="addMapDeviceClick(zzItem)"
            ></i>
            <!-- 装置地图要素删除 -->
            <i
              v-else
              title="删除标注"
              class="map-delete"
              @click.stop="delMapDeviceClick(zzItem)"
            ></i>

            <!-- 装置数据删除 -->
            <i title="删除数据" @click.stop="delDevice(zzItem)"></i>
          </div>
        </div>
        <!-- 三级目录 -->
        <div
          v-if="zzItem.searchInfoChild.length < 1 || zzItem.searchInfoChild[0].bm === 'dyxx'"
          class="device-card-content"
        >
          <el-collapse v-model="dyActive">
            <el-collapse-item
              v-for="(dyItme, dyIndex) in zzItem.searchInfoChild"
              :key="dyIndex"
              class="device-card-item"
              :class="{ 'unit-active': dyItme.id === tankUnitIndex }"
              :name="dyIndex"
              @click.stop="activeUnitClick(dyItme, zzItem)"
            >
              <template #title>
                <div style="display: flex; align-items: center">
                  <i></i>
                  <span class="single-line-text-exceeds" style="width: 230px" :title="dyItme.mc">{{
                    dyItme.mc
                  }}</span>
                </div>
                <div class="card-operation-btn">
                  <!-- 单元数据修改 -->
                  <i title="编辑表单" @click.stop="updateUnitClick(dyItme)"></i>

                  <!-- 单元地图要素上图 -->
                  <i
                    v-if="dyItme.sfbh === 0"
                    title="标注"
                    class="map-add"
                    @click.stop="addMapUnitClick(dyItme)"
                  ></i>
                  <!-- 单元地图要素删除 -->
                  <i
                    v-else
                    title="删除标注"
                    class="map-delete"
                    @click.stop="delMapUnitClick(dyItme)"
                  ></i>

                  <!-- 单元数据删除 -->
                  <i title="删除数据" @click.stop="delUnit(dyItme)"></i>
                </div>
              </template>

              <div
                v-for="(sbItem, sbIndex) in dyItme.searchInfoChild"
                :key="sbIndex"
                class="collapse-content-item"
              >
                <div
                  :class="{ 'device-active': sbItem.id === equipmentActiveIndex }"
                  @click.stop="activeEquipmentClick(sbItem, dyItme, zzItem)"
                >
                  <div :title="sbItem.bh + '   ' + sbItem.mc" style="display: flex">
                    <span
                      class="single-line-text-exceeds"
                      style="max-width: 50px; margin-right: 5px"
                      >{{ sbItem.bh }}</span
                    >
                    <span style="max-width: 60px" class="single-line-text-exceeds">{{
                      sbItem.mc
                    }}</span>
                  </div>
                  <div class="card-operation-btn">
                    <!-- 设备数据修改 -->
                    <i title="编辑表单" @click.stop="updateEquipmentClick(sbItem, 'dy')"></i>

                    <!-- 设备地图要素上图 -->
                    <i
                      v-if="sbItem.sfbh === 0"
                      title="标注"
                      class="map-add"
                      @click.stop="addMapEquipmentClick(sbItem)"
                    ></i>
                    <!-- 设备地图要素删除 -->
                    <i
                      v-else
                      title="删除标注"
                      class="map-delete"
                      @click.stop="delMapEquipmentClick(sbItem)"
                    ></i>

                    <!-- 设备数据删除 -->
                    <i title="删除数据" @click.stop="delEquipment(sbItem)"></i>
                  </div>
                </div>
              </div>

              <div class="collapse-content-item">
                <div @click.stop="addEquipmentClick(dyItme, 'dy')">
                  <i></i>
                  <span>新增设备</span>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

        <!-- 二级目录 -->
        <div
          v-else
          class="el-collapse-item__content"
          style="display: flex; flex-wrap: wrap; padding-bottom: 0"
        >
          <div
            v-for="(sbItem, sbIndex) in zzItem.searchInfoChild"
            :key="sbIndex"
            class="sb-collapse-content-item"
          >
            <div
              :class="{ 'device-active': sbItem.id === equipmentActiveIndex }"
              @click.stop="activeEquipmentClick(sbItem, null, zzItem)"
            >
              <div :title="sbItem.bh + '   ' + sbItem.mc" style="display: flex">
                <span class="single-line-text-exceeds" style="max-width: 50px; margin-right: 5px">{{
                  sbItem.bh
                }}</span>
                <span style="max-width: 60px" class="single-line-text-exceeds">{{
                  sbItem.mc
                }}</span>
              </div>
              <div class="card-operation-btn">
                <!-- 设备数据修改 -->
                <i title="编辑表单" @click.stop="updateEquipmentClick(sbItem, 'zz')"></i>

                <!-- 设备地图要素上图 -->
                <i
                  v-if="sbItem.sfbh === 0"
                  title="标注"
                  class="map-add"
                  @click.stop="addMapEquipmentClick(sbItem)"
                ></i>
                <!-- 设备地图要素删除 -->
                <i
                  v-else
                  title="删除标注"
                  class="map-delete"
                  @click.stop="delMapEquipmentClick(sbItem)"
                ></i>

                <!-- 设备数据删除 -->
                <i title="删除数据" @click.stop="delEquipment(sbItem)"></i>
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="zzItem.searchInfoChild.length < 1 || zzItem.searchInfoChild[0].bm === 'dyxx'"
          class="device-card-bottom"
          @click.stop="addUnitClick(zzItem)"
        >
          <i></i>
          <span>新增单元/子装置/工艺段/区</span>
        </div>
        <div
          v-if="zzItem.searchInfoChild.length < 1 || zzItem.searchInfoChild[0].bm === 'sbxx'"
          class="device-card-bottom"
          style="margin-top: 10px"
        >
          <div @click.stop="addEquipmentClick(zzItem, 'zz')">
            <i></i>
            <span>新增设备</span>
          </div>
        </div>
      </div>
    </div>

    <div class="card-footer" @click="addDeviceClick">
      <i></i>
      <span>新增装置</span>
    </div>
  </div>

  <!-- 删除数据二次确认弹窗 -->
  <SecondaryConfirm @secondaryConfirmSave="secondaryConfirmSave" />
</template>

<style lang="less" scoped>
.device-active {
  border: 1px solid #02979b !important;
}

.unit-active {
  /deep/.el-collapse-item__header {
    border: 1px solid #02979b !important;
    background: rgba(2, 151, 155, 0.4) !important;
  }
}

.device-container {
  height: 100%;
  .device-main {
    height: calc(100% - 100px);
    overflow: auto;
    .device-card {
      position: relative;
      margin-bottom: 15px;
      padding: 10px;
      background-color: rgba(0, 0, 0, 0.6);
      border-radius: 10px;
      cursor: pointer;
      .device-card-top {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        margin-bottom: 10px;
        & > div:nth-child(1) {
          i {
            display: inline-block;
            width: 32px;
            height: 32px;
            margin-top: -6px;
            margin-right: 2px;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            background-image: url(@/assets/image/productionStorage/zz-icon.png);
            vertical-align: middle;
          }
        }
      }
      .device-card-content {
        // max-height: 300px;
        // overflow: auto;
        margin-bottom: 10px;
        /deep/.el-collapse {
          border: 0;
        }
        .device-card-item {
          margin-bottom: 10px;
          /deep/.el-collapse-item__header {
            position: relative;
            height: 36px;
            border: 1px solid #797979;
            color: #fff;
            background: rgba(109, 109, 109, 0.2);
            border: 1px solid #6d6d6d;
            font-size: 16px;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            & > div:first-child {
              i {
                display: inline-block;
                width: 20px;
                height: 16px;
                margin: -6px 5px 0 10px;
                background-image: url(@/assets/image/productionStorage/dy-icon.png);
                background-size: 100% 100%;
                background-repeat: no-repeat;
                vertical-align: middle;
              }
            }
            .card-operation-btn {
              position: absolute;
              right: 40px;
            }
          }
          /deep/.el-collapse-item__wrap {
            background-color: unset;
            border: 1px solid #797979;
            border-top: 0;
          }
          /deep/.el-collapse-item__content {
            display: flex;
            flex-wrap: wrap;
            padding-top: 5px;
            padding-bottom: 0;
          }
        }
      }

      .collapse-content-item {
        flex: 0 0 33.3333%;
        & > div {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          margin: 5px;
          height: 58px;
          text-align: center;
          background-color: rgba(51, 51, 51, 0.5);
          color: #fff;
          border: 1px solid #797979;
          border-radius: 4px;
          box-sizing: border-box;
          i {
            width: 20px;
            height: 20px;
          }
          i:last-child {
            margin-right: 0;
          }
          span {
            font-size: 14px;
          }
        }
      }

      .sb-collapse-content-item {
        flex: 0 0 33.3333%;
        & > div {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          margin: 5px;
          height: 58px;
          text-align: center;
          background-color: rgba(51, 51, 51, 0.5);
          color: #fff;
          border: 1px solid #797979;
          border-radius: 4px;
          box-sizing: border-box;
          i {
            width: 20px;
            height: 20px;
          }
          i:last-child {
            margin-right: 0;
          }
          span {
            font-size: 14px;
          }
        }
      }

      .collapse-content-item:last-child {
        & > div {
          align-items: center;
          border: 1.5px dashed #797979;
          cursor: pointer;
          i {
            display: inline-block;
            width: 18px;
            height: 18px;
            margin-right: 5px;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            background-image: url(/src/assets/image/common/plus-icon.png);
          }
        }
      }

      .device-card-bottom {
        height: 38px;
        line-height: 38px;
        text-align: center;
        border: 1.5px dashed #6d6d6d;
        background: rgba(109, 109, 109, 0.2);
        border-radius: 4px;
        box-sizing: border-box;
        cursor: pointer;
        i {
          display: inline-block;
          width: 28px;
          height: 28px;
          margin-top: -5px;
          margin-right: 5px;
          background-size: 100% 100%;
          background-repeat: no-repeat;
          background-image: url(@/assets/image/common/plus-icon.png);
          vertical-align: middle;
        }
      }
    }
    .device-card:last-child {
      margin-bottom: 0;
    }
  }

  /deep/.el-collapse-item__arrow {
    color: #02979b;
    font-size: 24px;
  }
}
</style>
